package com.xxx.mq;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.xxx.constant.VerificationConstant;
import com.xxx.domain.CourseOrder;
import com.xxx.exception.GlobleBussnessException;
import com.xxx.service.ICourseOrderService;
import com.xxx.util.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * 消费订单发送的事务消息
 */
@RocketMQMessageListener(
        consumerGroup = "service-order-consumer-timeoutorder"
        , topic = VerificationConstant.MQ_TOPIC_TIMEOUT_ORDER
        , selectorExpression = VerificationConstant.MQ_TAGS_TIMEOUT_ORDER,
        messageModel = MessageModel.BROADCASTING  //广播
)
@Component
@Slf4j
public class TimeOutOrderconsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private ICourseOrderService courseOrderService;

    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            // 获取到消息
            if (messageExt != null && messageExt.getBody() != null && messageExt.getBody().length > 0) {
                byte[] body = messageExt.getBody();
                String orderNo = new String(body, StandardCharsets.UTF_8);  //订单号
                //查询订单状态
                EntityWrapper<CourseOrder> wrapper = new EntityWrapper<>();
                wrapper.eq("order_no", orderNo);
                CourseOrder courseOrder = courseOrderService.selectOne(wrapper);
                AssertUtil.isNotNull(courseOrder, "订单不存在");
                if (courseOrder.getStatusOrder() == 0) {
                    //订单超时关闭,修改订单状态
                    courseOrder.setStatusOrder(VerificationConstant.ORDER_STATUS_PAY_CANCEL);
                    courseOrderService.updateById(courseOrder);
                    log.info("订单超时关闭: " + orderNo);
                } else {
                    log.info("订单已支付: " + orderNo);
                }

            } else {
                log.warn("收到空消息或消息体为空");
            }
        } catch (Exception e) {
            log.error("处理支付订单消息失败: ", e);
            throw new GlobleBussnessException("生成支付单失败: " + e.getMessage());
        }
    }
}
